const LRUCache = require('lru-cache')
import md5 from 'md5'

const cacheCfg = new LRUCache({
  maxAge: 60 * 10e2,
  max: 1000
})

export default function(req, res, next){
  if (process.env.NODE_ENV === 'production'){
    let url = req._parsedOriginalUrl
    let pathname = url.path
    let key = md5(pathname)
    const existsHtml = cacheCfg.get(key)
    if(existsHtml){
      if (process.env.LOGGER_LEVEL === 'info') {
        // eslint-disable-next-line no-console
        console.log('This is use cache html, the request url is %s, the cache key is %s.', pathname, key)
      }
      return res.end(existsHtml.html, 'utf-8')
    }else{
      res.original_end = res.end
      res.end = function(data) {
        if (res.statusCode === 200) {
          if (process.env.LOGGER_LEVEL === 'info') {
            // eslint-disable-next-line no-console
            console.log('Cache request %s is done, the html is %s.', pathname, key)
          }
          cacheCfg.set(key, { html: data })
        }
        res.original_end(data, 'utf-8')
      }
    }
  }
  next()
}
